import {
  Component,
  OnInit,
  HostBinding,
  Input,
  Host,
  OnDestroy,
} from '@angular/core';
import { TableHeadComponent } from './table-head.component';
import { TableSortService, SortItem, SortOrder } from './table-sort.service';

@Component({
  selector: 'fui-table-head-cell',
  templateUrl: './table-head-cell.component.html',
})
export class TableHeadCellComponent implements OnInit, OnDestroy {
  @HostBinding('class.fui-table-head-cell') hostClass = true;

  /** Attribute key used for sorting. */
  @Input() sortKey: string;

  /** Sort order, support 'desc', 'asc'. */
  @Input() sortOrder: SortOrder;

  sortItem: SortItem;

  get sortIconColor() {
    const {sortOrder} = this.sortItem;
    if (sortOrder === 'desc' || sortOrder === 'asc') {
      return 'primary';
    } else {
      return 'secondary';
    }
  }

  get isAscend() {
    return this.sortItem.sortOrder === 'asc';
  }

  constructor(private tableSort: TableSortService) { }

  ngOnInit() {
    this.sortItem = new SortItem(this.sortKey, null);
    if (this.sortOrder) {
      this.sortItem.sortOrder = this.sortOrder;
    }
    this.tableSort.registerSortItem(this.sortItem);
  }

  ngOnDestroy() {
    this.tableSort.unregisterSortItem(this.sortKey);
  }

  clickSort() {
    this.sortItem.nextOrder();
    this.tableSort.sortChange(this.sortKey);
  }

}
